import {accessToken, instanceUrl} from "./constants";
import getShortcutByName from "./getShortcutByName";
import axios from "axios";

const putShortcutViewstates = async (name: string, viewstates: string)=> {
  const response = await getShortcutByName(name);
  if (!response.shortcut) {
    return;
  }
  const shortcut = response.shortcut;
  const id = shortcut.id;

  const normalizedUrl = instanceUrl.replace(/\/+$/, "");
  const body = JSON.stringify({
    "id": id,
    "comments": viewstates,
  });
  const resp = await axios.put(`${normalizedUrl}/api/v1/shortcuts/${id}?updateMask=comments`, body, {
    headers: {
      Authorization: `Bearer ${accessToken}`,
    },
  });
  if (resp.status !== 200) {
    throw Error(`updateShortcutViewstate error: ${resp.statusText}, status code ${resp.status}`);
  }
  return resp.data;
}

export default putShortcutViewstates;
